package com.bawei.mdm2207alast.apps

import android.app.DownloadManager
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.snapshots.SnapshotStateList
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import coil.compose.AsyncImage
import com.bawei.mdm2207alast.App
import com.bawei.mdm2207alast.R
import com.bawei.mdm2207alast.base.OnError
import com.bawei.mdm2207alast.base.OnLoading
import com.bawei.mdm2207alast.base.OnSuccess
import com.bawei.mdm2207alast.common.BaseTitle
import com.bawei.mdm2207alast.model.AppsEntity
import com.bawei.mdm2207alast.model.DownloadUtil
import com.blankj.utilcode.util.AppUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

/**
 * 作者：赵亮
 * 时间：2024/12/16 15:32
 * 功能：在线应用页面
 */
@Composable
fun OnLineAppsPage(
    navController: NavController = rememberNavController(),
    viewModel: AppsViewModel = hiltViewModel()
) {

    // 上下文
    val context = LocalContext.current

    // 注册一个下载完成的广播接收器
    context.registerReceiver(object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent) {
            val downloadManager =
                context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
            AppUtils.installApp(
                downloadManager.getUriForDownloadedFile(
                    p1.getLongExtra(
                        DownloadManager.EXTRA_DOWNLOAD_ID,
                        -1
                    )
                )
            )
        }
    }, IntentFilter("android.intent.action.DOWNLOAD_COMPLETE"))

    // 1. 数据
    val list = remember {
        SnapshotStateList<AppsEntity.Data>()
    }
    LaunchedEffect(key1 = "") {
        launch {
            // 更新状态/数据
            viewModel.uiState.collect {
                when (it) {
                    is OnError -> {
                        ToastUtils.showShort(it.msg)
                    }

                    OnLoading -> {}
                    is OnSuccess<*> -> {
                        list.addAll((it.data as AppsEntity).data)
                    }
                }
            }
        }
        launch {
            // 发送意图
            viewModel.sendIntent(AppsIntent.SelClientApp(mapOf("userId" to 1, "page" to 1)))
        }
    }
    Column {
        BaseTitle(navController, "在线应用")
        // 2. 展示
        Spacer(modifier = Modifier.height(10.dp))
        list.forEach {
            // 展示一级标题
            Text(text = it.title)
            // 网格展示应用列表
            LazyVerticalGrid(
                columns = GridCells.Fixed(3),
                verticalArrangement = Arrangement.spacedBy(5.dp)
            ) {
                items(it.appsList) {

                    // 是否显示下载对话框
                    var isShow by remember {
                        mutableStateOf(false)
                    }

                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        modifier = Modifier.clickable {
                            // 显示下载提示对话框
                            isShow = true
                        }) {
                        // 应用图片
                        AsyncImage(
                            placeholder = painterResource(id = R.drawable.icon64),
                            error = painterResource(id = R.drawable.icon1907),
                            model = it.appIcon.replace(
                                "http://10.161.9.80:8383",
                                "https://47ee78mh3302.vicp.fun"
                            ),
                            contentDescription = "",
                            modifier = Modifier.size(30.dp)
                        )

                        // 应用名称
                        Text(text = it.appName)
                    }

                    if (isShow) {
                        // 下载提示对话框
                        AlertDialog(
                            title = { Text(text = "下载提示！") },
                            text = { Text(text = "确定要下载${it.appName}吗?大概需要消耗${it.appSize}M流量") },
                            onDismissRequest = { isShow = false },
                            dismissButton = {
                                Text(text = "取消", modifier = Modifier.clickable {
                                    isShow = false
                                })
                            },
                            confirmButton = {
                                Text(text = "确定", modifier = Modifier.clickable {
                                    isShow = false
                                    viewModel.sendIntent(
                                        AppsIntent.DownloadApp(
                                            context,
                                            it.apkUrl.replace(
                                                "http://10.161.9.80:8383",
                                                "https://47ee78mh3302.vicp.fun"
                                            ),
                                            it.apkUrl.split("=")[1]
                                        )
                                    )
                                })
                            })
                    }
                }
            }

        }

    }
}


@Preview(showSystemUi = true)
@Composable
fun OnLineAppsPagePreview() {
    OnLineAppsPage()
}

